import { Edit, RefreshCw, Save, X } from "lucide-react";
import { useEffect, useId, useState } from "react";
import type { MeUpdateInput } from "../../../apis/me/me.types";
import useMeStore from "../../../store/me";

export default function MeBasicUpdator() {
  const meStore = useMeStore();
  const [nickname, setNickname] = useState<string>("");
  const [isEditing, setIsEditing] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const inputId = useId(); // 生成唯一 ID 用于关联 label 和 input

  // 加载用户信息
  useEffect(() => {
    if (meStore.me.type === "init") {
      meStore.loadMe();
    }
  }, [meStore]);

  // 当用户信息更新时，更新本地状态
  useEffect(() => {
    if (meStore.me.type === "ok") {
      setNickname(meStore.me.data.nickname);
    }
  }, [meStore.me]);

  // 处理编辑按钮点击
  const handleEditClick = () => {
    setIsEditing(true);
    setError(null);
  };

  // 处理取消编辑
  const handleCancelEdit = () => {
    setIsEditing(false);
    setError(null);
    // 如果用户信息已加载，则恢复原始昵称
    if (meStore.me.type === "ok") {
      setNickname(meStore.me.data.nickname);
    }
  };

  // 处理表单提交，更新昵称
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // 验证昵称
    if (!nickname.trim()) {
      setError("昵称不能为空");
      return;
    }

    setIsSubmitting(true);
    setError(null);

    try {
      const input: MeUpdateInput = { nickname: nickname.trim() };
      await meStore.updateMe(input);
      setIsEditing(false);
    } catch (_error) {
      setError("更新昵称失败，请稍后再试");
    } finally {
      setIsSubmitting(false);
    }
  };

  // 渲染加载状态
  if (meStore.me.type === "loading") {
    return (
      <div className="p-6 card">
        <div className="card-body">
          <h2 className="card-title">基本信息</h2>
          <div className="animate-pulse">
            <div className="h-10 bg-base-200 rounded w-1/4"></div>
          </div>
        </div>
      </div>
    );
  }

  // 渲染初始状态或加载失败状态
  if (meStore.me.type === "init") {
    return (
      <div className="p-6 card">
        <div className="card-body">
          <h2 className="card-title">基本信息</h2>
          <div className="text-neutral-content">加载用户信息失败，请刷新页面重试</div>
          <button type="button" onClick={meStore.loadMe} className="btn btn-primary mt-4">
            <RefreshCw className="h-4 w-4" />
            刷新
          </button>
        </div>
      </div>
    );
  }

  // 渲染用户昵称展示和编辑表单
  return (
    <div className="p-6">
      <h2 className="text-xl font-semibold mb-6">基本信息</h2>

      <div className="space-y-6">
        <div className="card bg-base-100 shadow-xl">
          <div className="card-body">
            <h3 className="text-lg font-medium">昵称设置</h3>

            {!isEditing ? (
              // 展示模式
              <div className="flex items-center justify-between">
                <div className="text-gray-800">
                  当前昵称：
                  <span className="font-medium">{meStore.me.data.nickname}</span>
                </div>
                <button type="button" onClick={handleEditClick} className="btn btn-primary">
                  <Edit className="h-4 w-4" />
                  编辑
                </button>
              </div>
            ) : (
              // 编辑模式
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="form-control">
                  <label htmlFor={inputId} className="label">
                    <span className="label-text">新昵称</span>
                  </label>
                  <input
                    type="text"
                    id={inputId}
                    value={nickname}
                    onChange={(e) => setNickname(e.target.value)}
                    className="input input-bordered"
                    placeholder="请输入新昵称"
                    maxLength={20}
                  />
                </div>

                {error && <div className="text-error text-sm">{error}</div>}

                <div className="card-actions justify-end">
                  <button type="button" onClick={handleCancelEdit} className="btn btn-outline" disabled={isSubmitting}>
                    <X className="h-4 w-4" />
                    取消
                  </button>
                  <button
                    type="submit"
                    className={`btn ${isSubmitting ? "btn-disabled" : "btn-primary"}`}
                    disabled={isSubmitting}
                  >
                    {isSubmitting ? (
                      <>
                        <span className="loading loading-spinner loading-sm mr-2"></span>
                        保存中...
                      </>
                    ) : (
                      <>
                        <Save className="h-4 w-4" />
                        保存
                      </>
                    )}
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
